import { ThemedView } from "@/components/ThemedView";
import { Feather } from "@expo/vector-icons";
import FontAwesome from "@expo/vector-icons/FontAwesome";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import Constants from "expo-constants";
import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import {
  Alert,
  Dimensions,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
  mediaDevices,
  RTCView,
  type MediaStream,
  RTCPeerConnection,
} from "react-native-webrtc";

export default function VideoCall() {
  const [micState, setMicState] = useState(true);
  const [textState, setTextState] = useState(false);
  const [cameraState, setCameraState] = useState(true);
  const insets = useSafeAreaInsets();
  const [stream, setStream] = useState<MediaStream | null>();
  const [offer, setOffer] = useState<any>();

  //获取屏幕大小
  const { width, height } = Dimensions.get("window");

  //控制路由跳转
  const router = useRouter();

  //创建webrtc连接
  const rtcConfiguration: RTCConfiguration = {
    iceServers: [
      {
        //这里是我自己的自建ICE服务器
        urls: ["stun:rocc.uno:3478", "turn:rocc.uno:3478"],
        username: "dpengchen",
        credential: "dpengchen",
      },
    ],
  };
  const rtcPeercConnection = new RTCPeerConnection(rtcConfiguration);
  //创建offer
  const createOffer = async () => {
    const offer = await rtcPeercConnection.createOffer({
      offerToReceiveAudio: 1,
      offerToReceiveVideo: 1,
    });
    console.log(offer);

    setOffer(offer);
    //将offer放入自己的描述
    rtcPeercConnection.setLocalDescription(offer);
  };

  //监听是否打开视频
  useEffect(() => {
    //如果是开启则加载视频
    if (cameraState) {
      userVideo();
    } else {
      //否则关闭视频输出
      stopUserVideo();
    }
  }, [cameraState]);

  //获取视频
  const userVideo = async () => {
    try {
      const s = await mediaDevices.getUserMedia({ video: true, audio: true });
      //添加媒体流
      rtcPeercConnection.addTrack(s.getVideoTracks()[0], s);
      setStream(s);
      // TODO 模拟测试
      // if (s.getAudioTracks.length == 0 || s.getVideoTracks.length == 0){
      //     throw new Error('未授权');
      // }
    } catch (e) {
      console.log("Error:", e);
      Alert.alert("未授权", "在应用设置中允许使用视频/音频进行通话之后重试。", [
        {
          text: "确定",
          onPress: () => {
            //重新询问权限
            router.back();
          },
        },
      ]);
    }
  };

  //关闭视频
  const stopUserVideo = () => {
    stream?.getTracks().forEach((track: any) => track?.stop());
  };

  useEffect(() => {
    //获取视频
    userVideo();
    //添加视频流到里面
    //创建offer
    createOffer();

    //离开页面时停止视频
    return () => {
      stopUserVideo();
      console.log("销毁组件");
    };
  }, []);

  return (
    <ThemedView
      style={{
        marginTop: Constants.statusBarHeight,
      }}
    >
      {/*显示视频内容*/}
      <View className={"bg-blue-300 w-full h-full"}>
        <RTCView
          streamURL={stream?.toURL()}
          style={{
            width: "100%",
            height: "100%",
            transformOrigin: "center",
            transform: [{ scaleX: -1 }],
          }}
          objectFit="cover"
        />
      </View>

      {/*显示自己*/}
      {cameraState ? (
        <View
          className={"absolute right-0 bg-yellow-200"}
          style={{ width: 120, height: 200, margin: 4 }}
        ></View>
      ) : null}

      {/*侧边功能区*/}
      <View
        className={"absolute"}
        style={{ top: cameraState ? 230 : 15, right: 5 }}
      >
        <TouchableOpacity
          className={"flex justify-center items-center bg-white mb-2"}
          style={{ width: 40, height: 40, borderRadius: 40 }}
          onPress={() => setTextState(!textState)}
        >
          {<MaterialIcons name="text-fields" size={20} color="black" />}
        </TouchableOpacity>
        <TouchableOpacity
          className={"flex justify-center items-center bg-white mb-2"}
          style={{ width: 40, height: 40, borderRadius: 40 }}
        >
          {<MaterialIcons name="flip-camera-ios" size={24} color="black" />}
        </TouchableOpacity>
      </View>

      {/*底部功能区*/}
      <View
        className={"absolute bottom-0 w-full  "}
        style={{
          marginBottom: insets.bottom,
        }}
      >
        {/*文字输入框*/}
        {textState ? (
          <View className={"m-2 mb-4"}>
            <TextInput
              className={"p-2 border-b border-solid border-white text-gray-700"}
              placeholder={"此处输入文字..."}
            />
          </View>
        ) : null}

        {/*功能按钮*/}
        <View className={"flex flex-row justify-around p-5 items-center "}>
          {/*麦克风*/}
          <TouchableOpacity
            onPress={() => setMicState(!micState)}
            className={"flex justify-center items-center bg-white"}
            style={{ width: 70, height: 70, borderRadius: 70 }}
          >
            {micState ? (
              <Feather name="mic" size={34} color="black" />
            ) : (
              <Feather name="mic-off" size={34} color="black" />
            )}
          </TouchableOpacity>

          {/*挂断按钮*/}
          <TouchableOpacity
            className={"flex justify-center items-center bg-red-600"}
            style={{ width: 80, height: 80, borderRadius: 80 }}
            onPress={() => router.back()}
          >
            <FontAwesome name={"phone"} size={55} color={"white"} />
          </TouchableOpacity>

          {/*切换摄像头还是文字输入*/}
          <TouchableOpacity
            className={"flex justify-center items-center bg-white"}
            style={{ width: 70, height: 70, borderRadius: 70 }}
            onPress={() => setCameraState(!cameraState)}
          >
            {cameraState ? (
              <Feather name="camera" size={34} color="black" />
            ) : (
              <Feather name="camera-off" size={34} color="black" />
            )}
          </TouchableOpacity>
        </View>
      </View>
    </ThemedView>
  );
}
